package com.zkyc.framework.file.util;

import com.luciad.imageio.webp.WebPReadParam;
import com.luciad.imageio.webp.WebPWriteParam;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

public class ImageUtils {

    public static String pngSuffix = "png";

    public static String jpgSuffix = "jpg";

    public static String jpegSuffix = "jpeg";

    public static String bmpSuffix = "bmp";


    public static String getFileExtension(String fileName) {
        String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
        return extension;
    }


    //判断是否是图片
    public static boolean isImage(String fileName) {
        String extension = getFileExtension(fileName);
        String[] imageExtension = new String[]{"jpeg", "jpg", "bmp", "png"};

        for (String e : imageExtension){
            if (extension.toLowerCase().equals(e)) {
                return true;
            }
        }

        return false;
    }

    public void toWebp(URL inputUrl,String outputWebpPath) throws IOException {
        //String inputPngPath = "src/main/resources/images/panda.png";
        //String inputJpgPath = "src/main/resources/images//panda.jpg";
        //URL inputJpgPath = new URL("http://10.101.116.7:9000/zj-lab/c854da81-bb2f-4f91-8e4f-d0986fff0a2e.jpg");
        //String outputWebpPath = "src/main/resources/images//hahahhaha.webp";

        // Obtain an image to encode from somewhere
        BufferedImage image = ImageIO.read(inputUrl);

        // Obtain a WebP ImageWriter instance
        ImageWriter writer = ImageIO.getImageWritersByMIMEType("image/webp").next();

        // Configure encoding parameters
        WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale());
        writeParam.setCompressionMode(WebPWriteParam.MODE_DEFAULT);

        // Configure the output on the ImageWriter
        writer.setOutput(new FileImageOutputStream(new File(outputWebpPath)));

        // Encode
        writer.write(null, new IIOImage(image, null, null), writeParam);
    }

    public void toImage(String inputWebpPath,String outputPath) throws IOException {
//        String inputWebpPath = "test_pic/test.webp";
//        String outputJpgPath = "test_pic/test_.jpg";
//        String outputJpegPath = "test_pic/test_.jpeg";
//        String outputPngPath = "test_pic/test_.png";

        // Obtain a WebP ImageReader instance
        ImageReader reader = ImageIO.getImageReadersByMIMEType("image/webp").next();

        // Configure decoding parameters
        WebPReadParam readParam = new WebPReadParam();
        readParam.setBypassFiltering(true);

        // Configure the input on the ImageReader
        reader.setInput(new FileImageInputStream(new File(inputWebpPath)));

        // Decode the image
        BufferedImage image = reader.read(0, readParam);
        ImageIO.write(image, "png", new File(outputPath));
//        ImageIO.write(image, "png", new File(outputPngPath));
//        ImageIO.write(image, "jpg", new File(outputJpgPath));
//        ImageIO.write(image, "jpeg", new File(outputJpegPath));
    }

    /**
     * 读取远程url图片,得到宽高
     * @param imgurl 图片路径
     * @return [0] 宽  [1]高
     */
    public static int[] getImgWH(String imgurl) {
        boolean b=false;
        try {
            //实例化url
            URL url = new URL(imgurl);
            //载入图片到输入流
            java.io.BufferedInputStream bis = new BufferedInputStream(url.openStream());
            //实例化存储字节数组
            byte[] bytes = new byte[100];
            //设置写入路径以及图片名称
            OutputStream bos = new FileOutputStream(new File("pic.jpg"));
            int len;
            while ((len = bis.read(bytes)) > 0) {
                bos.write(bytes, 0, len);
            }
            bis.close();
            bos.flush();
            bos.close();
            //关闭输出流
            b=true;
        } catch (Exception e) {
            //如果图片未找到
            b=false;
        }
        int[] a = new int[2];
        if(b){//图片存在
            //得到文件
            java.io.File file = new java.io.File("pic.jpg");
            BufferedImage bi = null;
            boolean imgwrong=false;
            try {
                //读取图片
                bi = javax.imageio.ImageIO.read(file);
                try{
                    //判断文件图片是否能正常显示,有些图片编码不正确
                    int i = bi.getType();
                    imgwrong=true;
                }catch(Exception e){
                    imgwrong=false;
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if(imgwrong){
                a[0] = bi.getWidth(); //获得 宽度
                a[1] = bi.getHeight(); //获得 高度
            }else{
                a=null;
            }
            //删除文件
            file.delete();
        }else{//图片不存在
            a=null;
        }
        return a;

    }

    //图片压缩
    public static InputStream compressImages(URL url) {
        try {
            //图片所在路径
            //BufferedImage templateImage = ImageIO.read(new URL("http://10.101.116.7:9000/zj-lab/94f4022a-cef5-42a7-8745-5f3bbabadcba.jpg"));
            BufferedImage templateImage = ImageIO.read(url);

            //原始图片的长度和宽度
            int height = templateImage.getHeight();
            int width = templateImage.getWidth();

            //通过比例压缩
            float scale = 0.95f;

            //通过固定长度压缩
            /*int doWithHeight = 100;
            int dowithWidth = 300;*/

            //压缩之后的长度和宽度
            int doWithHeight = (int) (scale * height);
            int dowithWidth = (int) (scale * width);

            BufferedImage finalImage = new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB);

            finalImage.getGraphics().drawImage(templateImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);

            //图片输出路径，以及图片名
/*            FileOutputStream  fileOutputStream = new FileOutputStream("d:/image/linghuAfterDoWith.jpg");
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fileOutputStream);
            encoder.encode(finalImage);
            fileOutputStream.close();*/
            return bufferedImageToInputStream(finalImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    //图片压缩
    public static InputStream compressImages(InputStream input) {
        try {
            BufferedImage templateImage = ImageIO.read(input);
            //原始图片的长度和宽度
            int height = templateImage.getHeight();
            int width = templateImage.getWidth();

            //通过比例压缩
            float scale = 0.95f;

            //压缩之后的长度和宽度
            int doWithHeight = (int) (scale * height);
            int dowithWidth = (int) (scale * width);

            BufferedImage finalImage = new BufferedImage(dowithWidth, doWithHeight, BufferedImage.TYPE_INT_RGB);
            finalImage.getGraphics().drawImage(templateImage.getScaledInstance(dowithWidth, doWithHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null);
            return bufferedImageToInputStream(finalImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 将BufferedImage转换为InputStream
     * @param image
     * @return
     */
    public static InputStream bufferedImageToInputStream(BufferedImage image){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            if (input.available() > 1002000){
                return compressImages(input);
            }
            return input;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}